import axios from 'axios'
// import { useUserStoreHook } from '@/store/modules/user'
import useCommonsStore from '@/store/modules/common'
import MessageBox from '@/components/MessageBox'

// 创建 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_API_BASEURL,
    timeout: 50000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        const commonsStore = useCommonsStore()
        if (commonsStore.token && config.isToken !== '1') {
            config.headers.Authorization = 'Bearer ' + commonsStore.token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const { data } = response
        if (response.status === 200) {
            if (!data.code == 0) {
                ElMessage.error(data.errMsg)
            }
            return data
        }

        ElMessage({
            message: data.message || '系统出错',
            type: 'error'
        })
        return Promise.reject(new Error(data.message || 'Error'))
    },
    error => {
        if (error.response.data) {
            // errorHandle(error.response);
            const { msg } = error.response.data
            // token 过期,重新登录
            if (error.response.status === 401) {
                MessageBox('当前页面已失效，请刷新或者重新登录')
                /* ElMessageBox.confirm('当前页面已失效，请刷新或者重新登录', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                }).then(() => {
                    localStorage.clear()
                    // window.location.href = '/'
                }) */
            } else {
                ElMessage.error(msg || '系统出错')
            }
        }
        return Promise.reject(error.message)
    }
)

// 导出 axios 实例
export default service
